import React, { useEffect, useRef, useState } from 'react'
import { ArrowLeft, Setting} from '@nutui/icons-react'
import { Success ,Cross } from '@react-vant/icons';
import { Button, Cell, Toast  } from 'react-vant';
import { useNavigate } from 'react-router-dom';
import { Popover } from 'antd-mobile' 
import './a.css'
import './face.less'
import axios from 'axios';
axios.defaults.baseURL = 'http://127.0.0.1:3000/logins'
// import 'animate.css';


import 'animate.css';

export default function Face() {
  //navigate
  const navigate = useNavigate()
  const [flag,setFlag]=useState(false)
  const [flag1,setFlag1]=useState(false)
  const Navigate = useNavigate()

  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const [capturedImages, setCapturedImages] = useState([]);

  // 隐藏警告
  const error = console.error;
  console.error = (...args) => {
    if (/defaultProps/.test(args[0])) return;
    error(...args);
  };

  //打开摄像头
  //该函数为异步函数，函数内部可以await关键字来等待异步操作的完成
  const startCamera = async () => {
    try {
      // navigator.mediaDevices.getUserMedia ({video:true}):这是Web Api中的一部分，
      //用于从用户设备获取媒体流（例如视频、音频）
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });
      if (videoRef.current) { //如果videoRef.current存在
        videoRef.current.srcObject = stream
      }
    } catch (error) {
      console.log('访问摄像头出错：', error)
      //处理错误 （例如向用户显示消息）
    }
  }

  // 关闭摄像头
  const closeMedia = () => {
    //获取videoRef引用的当前<video>元素
    const video = videoRef.current;
    //获取<video>元素的srcObject属性，这是一个MediaStream对象
    const stream = video.srcObject;
    //检查stream对象是否具有getTracks方法（用于获取所有媒体轨道）
    if ('getTracks' in stream) {
      //获取媒体流中的所有轨道（例如视频轨道、音频轨道等）
      const tracks = stream.getTracks();
      tracks.forEach(track => {
        track.stop(); //停止每个轨道，释放资源（例如停止摄像头或麦克风的使用）
      });
    }else{
      console.warn('无法获取媒体流中的轨道，可能存在媒体流设置问题')
    }
  }



  //
  const capture = () => {
    if (!canvasRef.current || !videoRef.current) return;

    const canvas = canvasRef.current;
    const context = canvas.getContext('2d');
    //绘制图像
    //将 videoRef.current 中当前的视频帧绘制到 <canvas> 上
    context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);

    //将 <canvas> 中的内容转换为 base64 编码的 JPEG 图像
    const imageSrc = canvas.toDataURL('image/jpeg');
    setCapturedImages([...capturedImages, imageSrc]);
    submitImages(imageSrc);
  }


  const submitImages = async(img)=>{
    try{
      const res = await axios.post('http://127.0.0.1:3000/logins/faceLogin',{b64:img});
      if(res.data.code == 200){
        setFlag(true)
        setTimeout(()=>{
          Navigate('/Login')
          setFlag(false)
        },2000)
      }
      if(res.data.code == 401){
        setFlag1(true)
        setTimeout(()=>{
          setFlag1(false)
        },2000)
      }
    } catch(error){
      console.log('提交图像出错',error)
      setFlag1(true)
    }
  }

  useEffect(() => {
    startCamera();
  }, [])

  return (
    <div id='face_zlq'>
      <div class="animate__animated animate__backInLeft">
      
      <img src="../../public/左.png" width="30rem" height="30rem" style={{ position: "absolute", top: "0.5rem" }} onClick={() => { Navigate('/Login') }}></img>
      <p style={{ textAlign: "center", lineHeight: "1.7rem", fontSize: "0.4rem"}}>人脸识别</p>

      <p>
        <h3 style={{ paddingLeft: '35px', display: 'block', marginTop: '10px', marginBottom: '-15px' }}>人脸登录</h3><br />
        <span style={{ fontSize: '14px', paddingLeft: '35px', color: 'red' ,display:flag1  ? 'block':'none'}}>请选择使用验证码或重新进行认证</span>
      </p>
      <div
        style={{
          height:"auto",
          marginTop: '70px',
          marginLeft:"40px",
          position:'relative'
        }}
      >
        {/* <Cell> */}
          <div className="kl">
            <video ref={videoRef}  autoPlay muted></video>
            <canvas ref={canvasRef}  style={{ }}></canvas>
          </div>
        {/* </Cell> */}

        <Button onClick={capture} style={{ width: '50%', margin: '50px auto' }} color='linear-gradient(to right, rgb(151, 185, 125), rgb(2,167,240))' type='primary' block round>开始认证</Button>

        <div className='mask_err' style={{display:flag1 ? 'block':'none'}}> <Cross style={{color:'white',fontSize:'60px',}}/></div>
        <div className='mask_success' style={{display:flag ? 'block':'none'}}> <Success style={{color:'white',fontSize:'60px'}}/></div>
      </div>

      <Popover
          content={
            <>
              <p style={{width:'100px',height:'35px'}} onClick={closeMedia}>关闭摄像头</p>
              <p style={{width:'100px',height:'35px'}} onClick={startCamera}>打开摄像头</p>
              {/* <img src='video.png' style={{width:'45px',height:'35px'}} onClick={}/> */}
            </>
          }
          trigger='click'
          placement='left-end'
          defaultVisible
        >
      <div style={{
        width: '35px',
        height: '35px',
        position: 'fixed',
        bottom: '70px',
        right: '20px',
        border: '1px solid #d5d5d5',
        borderRadius: '50px',
      }}>
        <Setting />
      </div>
      </Popover>
    </div>
    </div>
  )
}

